<?php
/*
# ------------------------------------------------------------------------
# JA Compress Plugin for Joomla 1.5
# ------------------------------------------------------------------------
# Copyright (C) 2004-2009 J.O.O.M Solutions Co., Ltd. All Rights Reserved.
# @license - GNU/GPL, http://www.gnu.org/copyleft/gpl.html
# Author: J.O.O.M Solutions Co., Ltd
# Websites:  http://www.joomlart.com -  http://www.joomlancers.com
# ------------------------------------------------------------------------
*/

// Prevent direct access
defined( '_JEXEC' ) or die();

class JACompressHelper extends JObject {
	// Plugin paramater
	var $_params;
	
	// Constructor
	function __construct($pluginParam){
		$this->_params = $pluginParam;
	}
	
	// Check file exist and cache time
	function checkCacheTime($fileName){
		if(file_exists($fileName)){
			$cacheTime	= $this->_params->get("general-cache", 60);
			$cacheTime	= $cacheTime*60*1000;
			$createdTime= time() - filectime($fileName);
			if($createdTime > $cacheTime)
				return false;
			else
				return true;
		}else
			return false;
	}
	
	// Get file content, optimize, and write file to cache folder.
	function writeCompileFile($arrData, $type="css"){
		// First, get file content.
		jimport('joomla.filesystem.file');
		$baseName 	= md5(JURI::root().implode("", $arrData)).".".$type;
		$fileName 	= JPATH_CACHE.DS."jacompress".DS.$baseName;
		$fileURL	= JURI::root()."cache/jacompress/".$baseName;
		
		// Check used GZip
		if($this->_params->get("general-gzip", 1) == 1){
			$fileName 	.= ".gz";
			$fileURL	= JURI::root()."plugins/system/plg_jacompress/getfile.php?type=".$type."&amp;file=".$baseName.".gz";
			if($this->checkCacheTime($fileName)){
				return $fileURL;
			}
		}else{
			if($this->checkCacheTime($fileName)){
				return $fileURL;
			}
		}
				
		$CSSString = "";
		foreach ($arrData as $string){			
			$string = str_replace("/", DS, $string);
			$file = JPATH_ROOT.DS.$string;
			
			$CSSString .= $this->optimizeString($file, $type)."\n";
			
			// Add JQuery no conflict function
			if($this->_params->get("js-jquery-avoid", 1) == 1 && strpos($string, $this->_params->get("js-jquery-filename", "jquery")) > 0 )
				$CSSString .= 'if (jQuery && jQuery.noConflict) jQuery.noConflict();'."\n";				
		}
		
		if( $this->_params->get("general-gzip", 1) == 1)
			JFile::write($fileName, gzencode($CSSString) );
		else
			JFile::write($fileName, $CSSString);
		
		
		return $fileURL;
	}
	
	// Remove break, comment function
	function optimizeString($file, $type="css"){
		$string = "";
		if(file_exists($file)){
			$string .= file_get_contents($file);			
		}
		// Replace comment, line break
		if($type == "css"){
			
			$string = preg_replace('<\s*([@{}:;,]|\)\s|\s\()\s*|[\n\r]|/\*(.*)\*/>x', '\1', $string);
			
			// Replace url file path in CSS file: E.g: url(../image/bg.gif) => url(/modules/jatab/image/bg.gif)
			preg_match_all('/url\([\'"]?(?![a-z]+:|\/+)([^\'")]+)[\'"]?\)/i', $string, $data);
			
			$folder = str_replace(JPATH_ROOT.DS, "", dirname($file));
			if( strpos($folder, DS) == 0)
				$folder = str_replace(DS, "/", $folder)."/";
			else
				$folder = "/".str_replace(DS, "/", $folder)."/";
			
			$file = array();
			foreach($data[1] as $k=>$v){			
				if(! in_array($v, $file) )
					$string = str_replace($v, $folder.$v, $string);
				$file[] = $v;
			}
		}else{
			// Minimize javascrip file
			if(strpos($file, "mootools") === false && strpos($file, "jquery") === false){
				$string = preg_replace('!/\*.*?\*/!s', '', $string);
				$string = preg_replace('/\n\s*\n/', " ", $string);
				// $string = preg_replace('#//.*#', " ", $string);
				$string = preg_replace('/[\t]/e', " ", $string);
			}
		}
		// die();
		return $string;
	}
	
	function replaceHeaderFile($arrFile, $strReplace, $bodyString, $type="css"){
		$bodyString = explode("</head>", $bodyString);	
		$bodyString[0] = explode("\n", $bodyString[0]);	
		foreach($bodyString[0] as $k=>$link){
			foreach($arrFile as $css){
				if(strpos($link, $css) > 0){			
					if($type=="css")			
						$bodyString[0][$k] = substr($bodyString[0][$k], strpos($bodyString[0][$k], "<link"), strlen($bodyString[0][$k]) - strpos($bodyString[0][$k], "/>"));
					else
						$bodyString[0][$k] = substr($bodyString[0][$k], strpos($bodyString[0][$k], "<script"), strlen($bodyString[0][$k]) - strpos($bodyString[0][$k], "</script>"));
					if(count($bodyString[0][$k]) < 5)
						unset($bodyString[0][$k]);
				}
			}
		}
		
		$bodyString[0] = implode("\n", $bodyString[0]);
		$bodyString[0] = str_replace("</title>", "</title>"."\n".$strReplace, $bodyString[0]);
		$bodyString = $bodyString[0]."</head>".$bodyString[1];
		
		return $bodyString;
	}
	
	/* Get list of include files (CSS) in Body string
	 * $bodyString Body string
	 */
	function getJSFile($bodyString){
		// Get Avoid css files in Plugin config
		
		$arrAvoid 	= explode(",", $this->_params->get("js-avoid", ""));
		$arrJS		= $this->getCSSFile($bodyString, "/([^\"\'=]+\.(js))[\"\']/i", $arrAvoid);		
		
		// Reorder JavaScript file in array
		$newArr		= array();
		$arrOrder	= explode(",", $this->_params->get("js-javascript-order", ""));
		foreach ($arrOrder as $k=>$v){
			foreach ($arrJS as $i=>$j){
				if($v == $this->getFileName($j)){
					$tmp 		= $arrJS[$k];
					$arrJS[$k]	= $j;
					$arrJS[$i]	= $tmp;
				}
			}
		}
		
		return $arrJS;			
	}
	
	/* Get list of include files (CSS) in Body string
	 * $bodyString Body string
	 */
	function getCSSFile($bodyString, $regString="", $arrAvoid=array()){
		$arrResult	= array();		
		if(count($arrAvoid) == 0)
			$arrAvoid 	= $this->getAvoidCSSFile($bodyString);		
		if($regString == "")
	 		$regString = "/([^\"\'=]+\.(css))[\"\']/i";		
		preg_match_all($regString, $bodyString, $arrMatchs);				
		foreach($arrMatchs[1] as $k=>$string){			
			if(!in_array($this->getFileName($string), $arrAvoid)){				
				if(strpos($string, JURI::root()) !== false)
					$string	= str_replace(JURI::root(), "", $string);
				$arrResult[]	= $string;
			}			
		}
		
		return $arrResult;
	}
	
	// Analyst BodyString to get CSS files for IE 6,7,8...
	// Get avoid CSS files in Config file and match them.
	function getAvoidCSSFile($bodyString){
		$condition = array();		
		$conditionRegex="/<\!--\[if.*?\[endif\]-->/is";
	 	preg_match_all($conditionRegex,$bodyString,$conditonMatches);
	 	$linksRegex="|<link[^>]+[/]?>((.*)</[^>]+>)?|U";
				
	 	if(!empty($conditonMatches)){
	 		preg_match_all($linksRegex,@implode('',$conditonMatches[0]),$conditionCss);
			
			//die(print_r($conditionCss));
			
	 		if(!empty($conditionCss[0])){
	 			$cssRegex="/([^\"\'=]+\.(css))[\"\']/i";
	 			preg_match_all($cssRegex,@implode('',$conditionCss[0]),$conditionCssFiles);
				
	 			if(!empty($conditionCssFiles[1])){
	 				foreach($conditionCssFiles[1] as $conditionalCss){
	 					$condition[] = $this->getFileName($conditionalCss);
	 				}
	 			}
	 		}
	 	}
		// Get avoid css file in plugin config
		$avoid = explode(",", $this->_params->get("css-avoid", ""));
		
		$condition = array_merge($avoid, $condition);
		
		return $condition;
	}
	
	function getFileName($string){
		$name	=	strrchr($string,'/');
		$name	=	substr($name,1);
		if(isset($name)){
			return trim($name);
		}else{
			return $string;
		}
	}
}
?>